﻿#include"SeqList.h"

void SLInit(SL* ps)//顺序表数据的初始化
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}
void SLDestroy(SL* ps)//指针销毁
{
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLPrint(SL* ps)//打印顺序表
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}
void SLCheckCapacity(SL* ps)//arr扩容
{	
	int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
	SLTDataType* tmp = (SLTDataType*)realloc(ps->arr, newCapacity* sizeof(SLTDataType));
	if (tmp == NULL)//判断是否申请失败
	{
		perror("realloc fail!");
		exit(1);
	}
	ps->arr = tmp;
	ps->capacity = newCapacity;
}
void SLPushBack(SL* ps, SLTDataType x)//尾插
{
	assert(ps);//空间不够
	SLCheckCapacity(ps);//空间足够
	ps->arr[ps->size] = x;
	ps->size++;
}
void SLPushFront(SL* ps, SLTDataType x)//头插
{
	if (ps == NULL)
	{
		return;
	}
	SLCheckCapacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}
void SLPopBack(SL* ps)//尾删
{
	assert(ps && ps->size);//保证ps以及ps中的size不为空
	ps->size--;
}
void SLPopFront(SL* ps)//头删
{
	assert(ps && ps->size);//保证ps以及ps中的size不为空
	//数据整体前移
	for (int i = 0; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}  
	ps->size--;
}
int SLFind(SL* ps, SLTDataType x)//查找
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			printf("数据已找到\n");
			return i;
		}
	}
	return -1;
}//指定位置之前插⼊
void SLInsert(SL* ps, int pos, SLTDataType x){
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}
void SLInsertAfter(SL* ps, int pos, SLTDataType x)//在指定位置之后插入数据
{
	assert(ps);
	assert(pos-- > 0 && pos < ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}
//删除pos位置的数据
void SLErase(SL* ps, int pos){
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size; i++ ) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}